import { message } from "antd";
import request from "./request";

// 通用下载方法
export function download(url: string, params: any, fileName: string) {
  // prettier-ignore
  return request.post(url, params, {
      transformRequest: [
        (params: any) => {
          return tansParams(params);
        }
      ],
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob'
    }).then(async (resp: any) => {
      const isLogin = isBlob(resp);
      if (isLogin) {
        const blob = new Blob([resp]);
        const objectUrl = URL.createObjectURL(blob);
        const tmpLink = document.createElement("a");
        tmpLink.href = objectUrl;
        tmpLink.download = fileName;
        document.body.appendChild(tmpLink); 
        tmpLink.click();
        URL.revokeObjectURL(objectUrl);
      } 
    }).catch((r: any) => {
      console.log(r);
      message.error('下载文件出现错误，请联系管理员！');
    });
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export const tansParams = (params: any) => {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    const part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== "" &&
            typeof value[key] !== "undefined"
          ) {
            const params = propName + "[" + key + "]";
            const subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
};

// 判断是否是blob
export const isBlob = (data: any) => {
  return data.type !== "application/json";
};
